/*
 * Copyright (c) 2020, China Mobile Communications Group Co.,Ltd.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-11-14     cmcc       the first version
 */

#include "ns_log.h"

#include <os_stddef.h>

#include <webclient.h>
#include <cJSON.h>

#include "ns_auth.h"

int ns_get_auth_token(char* token_buffer)
{
    //no token file or refresh
    //build url
    char url[300] = URL_AUTH_TOKEN;
    strcat(url, "secret_key=");
    strcat(url, PKG_NINESKY_SECRET_KEY);
    strcat(url, "&api_key=");
    strcat(url, PKG_NINESKY_API_KEY);
    LOG_EXT_D("auth url:%s", url);

    char *buffer = OS_NULL;
    int length = webclient_request(url, OS_NULL, OS_NULL, (unsigned char**)&buffer);

    if (length < 0)
    {
        LOG_EXT_E("send GET fail, check your network");
        return -OS_ERROR;
    }

    LOG_EXT_D("recv:%s", buffer);

    /*
     sample:
     {
         "code":200,
         "msg":"",
         "data":{
             "access_token":""
         }
     }
    */

    cJSON* json = cJSON_Parse(buffer);
    if(json == NULL)
    {
        LOG_EXT_E("json error:%s\n", cJSON_GetErrorPtr());
        return -OS_ERROR;
    }

    cJSON* code = cJSON_GetObjectItem(json, "code");
    if(code->valueint != 200)
    {
        LOG_EXT_E("invalid token, code:%d, msg:%s", code->valueint, (cJSON_GetObjectItem(json, "msg"))->valuestring);
        return -OS_ERROR;
    }

    cJSON* data = cJSON_GetObjectItem(json, "data");
    cJSON* access_token = cJSON_GetObjectItem(data, "access_token");

    memcpy(token_buffer, access_token->valuestring, strlen(access_token->valuestring)+1);

    os_free(buffer);
    cJSON_Delete(json);

    return OS_EOK;
}
